package com.my.study.collections;

import lombok.extern.slf4j.Slf4j;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @author Carlos
 * @version 1.0
 * @Description 集合不安全
 * @date 2021/5/30 13:56
 **/
@Slf4j
public class ContainerNotSafe {

    public static void main(String[] args) {

        ContainerNotSafe containerNotSafe = new ContainerNotSafe();

        String str1 = "abc";
        containerNotSafe.changeStr(str1);
        System.out.println(str1);

        String ddd = new String("ddd");
        containerNotSafe.changeStr(ddd);
        System.out.println(ddd);

    }

    public void changeStr(String str) {
        str = "xxx";
        System.out.println(str);
    }

    public static void listNotSafe() {
        // 不安全
        List<String> list = new ArrayList<>();
        for (int i = 0; i < 30; i++) {
            new Thread(() -> {
                list.add(UUID.randomUUID().toString().substring(0, 8));
                System.out.println(list);
            }, String.valueOf(i)).start();
        }

        // 安全
        List<Integer> synchronizedList = Collections.synchronizedList(new ArrayList<>());
        List<Integer> copyOnWriteArrayList = new CopyOnWriteArrayList<>();

    }

    public static void setNotSafe() {
        // 不安全
        HashSet<Object> hashSet = new HashSet<>();

        //  安全
        Set<Object> synchronizedSet = Collections.synchronizedSet(new HashSet<>());
        CopyOnWriteArraySet<Object> copyOnWriteArraySet = new CopyOnWriteArraySet<>();

    }

    public static void mapNotSafe() {
        // 不安全
        HashMap<Object, Object> hashMap = new HashMap<>();

        // 安全
        ConcurrentHashMap<Object, Object> concurrentHashMap = new ConcurrentHashMap<>();

    }


}
